﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Server;
using System.Threading;

namespace PSE.Deployment.TeamFoundation.Communication
{
    public class PackageIterationBranch : CommunicationBase
    {
        #region Singleton
        private static PackageIterationBranch instance;
        protected PackageIterationBranch() 
        {
            Communication.VersionControl.Instance.TraceEvent += (sender, e) => RaiseEventTrace(e);
        }
        public static PackageIterationBranch Instance
        {
            get
            {
                if (instance == null)
                {
                    Mutex mutex = new Mutex();
                    mutex.WaitOne();

                    if (instance == null)
                        instance = new PackageIterationBranch();

                    mutex.Close();
                }
                return instance;
            }
        }
        #endregion Singleton

        public List<Entity.PackageIterationBranch> GetBranches(string sourceUri)
        {
            if (string.IsNullOrEmpty(sourceUri))
                throw new ArgumentNullException("sourceUri");

            RaiseEventTrace(string.Format("Obtendo os Branches do Uri {0}", sourceUri));

            List<Entity.PackageIterationBranch> branches = new List<Entity.PackageIterationBranch>();
            VersionControlServer versionControl = Communication.VersionControl.Instance.GetVersionControlServer();

            ItemSet tpItems = versionControl.GetItems(sourceUri, RecursionType.OneLevel);

            Uri parenteUri = new Uri(sourceUri.Replace("$", "/"));

            foreach (Item item in tpItems.Items)
            {
                Uri uri = new Uri(item.ServerItem.Replace("$", "/"));

                if (uri.Segments.Count() >= parenteUri.Segments.Count() + 1)
                {
                    Entity.PackageIterationBranch branch = new Entity.PackageIterationBranch();
                    branch.BranchVersion.Package = uri.Segments[uri.Segments.Count() - 1].Substring(1, 1);
                    branch.BranchVersion.Iteration = uri.Segments[uri.Segments.Count() - 1].Substring(3, 1);
                    RaiseEventTrace(string.Format("Adicionando o Branche {0}", branch.BranchVersion));
                    branches.Add(branch);
                }
            }
            return branches;
        }
    }
}
